package o2o.web.actions.notice;


import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.ToolUtils;
import com.jinyou.utils.common.ValidateUtil;
import notice.buzz.NoticeBusiness;
import notice.cache.UserOnlyInfoMemory;
import notice.dao.NoticeRange;
import notice.dao.NoticeType;
import notice.dao.NoticeVO;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.user.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
public class NoticeAction {

    //用户获取未读消息数量
    @RequestMapping(method = RequestMethod.POST, value = "/notice/unreadCount")
    @ResponseBody
    public String notice_unread_count(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        Map<String, Object> mapPara = new HashMap<>();
        mapPara.put("delFlag", 0);
        mapPara.put("isRead", 0); // 未读
        long count = NoticeBusiness.unreadCount(Long.valueOf(user.getUserType()), user.getUsername(), mapPara);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        return AjaxResult.successResult(map);
    }

    //用户获取消息列表
    @RequestMapping(method = RequestMethod.POST, value = "/notice/list")
    @ResponseBody
    public String notice_list(String token, Long timestamped) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (timestamped == null) {
            timestamped = Long.valueOf(0L);
        }
        int size = 0;
        if (timestamped.longValue() == 0L) {//如果时间戳为0 那么为第一次获取
            size = 40;
        } else {//不是第一次获取，检查是否有新消息
            long lastCreate = UserOnlyInfoMemory.getInstance().getLastNewNoticeTime(user.getUserType(), user.getUsername());//获取最新消息时间戳
            if (lastCreate <= timestamped.longValue()) {//如果最新时间戳比请求的还要小 那么没有最新的消息
                AjaxResult.successResult(0, null);
            }
        }

        //查询消息
        //Long orgId, String username, long createTim, int type, int size, int refreshType
        List list = NoticeBusiness.list(Long.parseLong(user.getUserType() + ""), user.getUsername(), timestamped.longValue(), NoticeType.all, size, 2);
        return AjaxResult.successResult(list != null ? list.size() : 0, list);
    }

    //管理后台通过页码获取系统通知
    @RequestMapping(method = RequestMethod.POST, value = {"/admin/notice/system/list"})
    @ResponseBody
    public String contest_list(String token, String toRange, Long page, Long size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (page == null || page < 1) {
            page = Long.valueOf(1L);
        }
        if (size == null || size < 1 || size > 30) {
            size = Long.valueOf(20L);
        }
        Long timestamped = Long.valueOf(1L);

        Long orgId = getOrgIdByToRange(toRange);
        List list = NoticeBusiness.systemNoticeList(orgId, timestamped, NoticeType.system, page.intValue() * size.intValue(), 1);
        list = ToolUtils.list(list, (page.intValue() - 1) * size.intValue() + 1, page.intValue() * size.intValue());

        HashMap mapPara = new HashMap();
        mapPara.put("delFlag", Integer.valueOf(0));
        mapPara.put("type", Integer.valueOf(NoticeType.system));
        long count = NoticeBusiness.count(orgId, mapPara);

        return AjaxResult.successResult(count, list != null ? list.size() : 0, list);
    }


    //设置消息为已读
    @RequestMapping(method = RequestMethod.POST, value = "/notice/read")
    @ResponseBody
    public String notice_read(String token, String msgIds) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        Long orgId = Long.parseLong(user.getUserType() + "");
        NoticeBusiness.readNotice(orgId, user.getUsername(), msgIds);

        //add by zhuwx 主表发送给单个对象
        orgId = NoticeAction.getOrgIdByToRange(NoticeRange.single);
        NoticeBusiness.readNotice(orgId, user.getUsername(), msgIds);

        return AjaxResult.successResult();
    }

    //发送系统通知
    @RequestMapping(method = RequestMethod.POST, value = "/notice/system/add")
    @ResponseBody
    public String notice_system_add(String token, String toRange, NoticeVO ntcvo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == ntcvo) {
            return AjaxResult.errorResult("请补全信息后重新提交");
        }
        if (ValidateUtil.isNull(toRange)) {//默认所有人
            toRange = NoticeRange.all;
        }
        ntcvo.setType(NoticeType.system);//消息类型：系统通知

        ntcvo.setRange(NoticeRange.getRangeName(toRange));

        Long orgId = getOrgIdByToRange(toRange);

        switch (toRange) {//发送对象
            case NoticeRange.all: {//所有用户
                HashMap<String, HashSet<String>> userMap = getAllUserMap();
                if (ValidateUtil.isAbsMap(userMap)) {
                    Iterator iter = userMap.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        Object key = entry.getKey();
                        Object val = entry.getValue();
                        if (null != key && null != val) {
                            NoticeBusiness.saveNotice(orgId, user.getUsername(), (HashSet<String>) val, ntcvo);
                        }
                    }
                }
            }
            break;
            case NoticeRange.shop: {//所有店家
                Set<String> userSet = getUserSet(UserType.SHOP_OWNER);
                if (null != userSet) {
                    NoticeBusiness.saveNotice(orgId, user.getUsername(), userSet, ntcvo);
                }

            }
            break;
            case NoticeRange.admin: {//所有管理员
                Set<String> userSet = getUserSet(UserType.ADMIN);
                if (null != userSet) {
                    NoticeBusiness.saveNotice(orgId, user.getUsername(), userSet, ntcvo);
                }

            }
            break;
            case NoticeRange.user: {//所有普通用户
                Set<String> userSet = getUserSet(UserType.USER);
                if (null != userSet) {
                    NoticeBusiness.saveNotice(orgId, user.getUsername(), userSet, ntcvo);
                }
            }
            break;
            case NoticeRange.postman: {//所有配送员
                Set<String> userSet = getUserSet(UserType.POSTMAN);
                if (null != userSet) {
                    NoticeBusiness.saveNotice(orgId, user.getUsername(), userSet, ntcvo);
                }
            }
            break;
            default: {//一部分人
                if (ValidateUtil.isNotNull(toRange)) {
                    String[] toUsers = toRange.split(",");
                    if (null != toUsers && toUsers.length > 0) {
                        for (int i = 0; i < toUsers.length; i++) {
                            if (ValidateUtil.isNotNull(toUsers[i])) {
                                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(toUsers[i]);
                                if (null != userInfo) {
                                    HashSet<String> userSet = new HashSet<>();
                                    userSet.add(userInfo.getUsername());
                                    NoticeBusiness.saveNotice(NoticeAction.getOrgIdByToRange(NoticeRange.single), user.getUsername(), userSet, ntcvo);
                                }
                            }
                        }
                    }
                }
            }
            break;
        }


        return AjaxResult.successResult();
    }

    //自动发布系统通知

    //todo
    //给指定人发送消息
    //订单操作

    //----------------------------
    //获取所有用户set
    private HashMap<String, HashSet<String>> getAllUserMap() {
        List<UserInfo> userList = UserInfoMemory.getInstance().list(0);//获取所有用户
        if (ValidateUtil.isAbsList(userList)) {
            HashMap<String, HashSet<String>> userMap = new HashMap<String, HashSet<String>>();

            for (int i = 0; i < userList.size(); i++) {
                if (null != userList.get(i)) {
                    HashSet<String> userSet = null;
                    if (null != userList.get(i)) {
                        if (!ValidateUtil.isNotAbsInteger(userList.get(i).getUserType())) {
                            userList.get(i).setUserType(-10);
                        }
                        if (userMap.containsKey(userList.get(i).getUserType() + "")) {
                            userSet = userMap.get(userList.get(i).getUserType() + "");
                        } else {
                            userSet = new HashSet<String>();
                        }
                        userSet.add(userList.get(i).getUsername());
                        userMap.put(userList.get(i).getUserType() + "", userSet);
                    }

                }
            }
            return userMap;
        }
        return null;
    }

    // 根据用户类型获取所有的用户账号
    private Set<String> getUserSet(int userType) {
        List<UserInfo> userList = UserInfoMemory.getInstance().list(userType);//获取所有用户
        if (userList != null && !userList.isEmpty()) {
            Set<String> uu = userList.stream().map(a -> a.getUsername()).collect(Collectors.toSet());
            return uu;
        }
        return null;
    }


    //-----------------------------
    //根据返回指定消息orgid
    public static Long getOrgIdByToRange(String toRange) {
        if (ValidateUtil.isNotNull(toRange)) {
            switch (toRange) {
                case NoticeRange.all: {
                    return Long.parseLong(UserType.ALL + "");
                }
                case NoticeRange.user: {
                    return Long.parseLong(UserType.USER + "");
                }
                case NoticeRange.shop: {
                    return Long.parseLong(UserType.SHOP_OWNER + "");
                }
                case NoticeRange.admin: {
                    return Long.parseLong(UserType.ADMIN + "");
                }
                case NoticeRange.postman: {
                    return Long.parseLong(UserType.POSTMAN + "");
                }
                case NoticeRange.single://SINGLE 或者不是前面几种类型的就是指定人员
                default: {
                    return Long.parseLong(UserType.SINGLE + "");
                }
            }
        } else {
            return Long.parseLong(UserType.ALL + "");//默认所有人
        }


    }


}

